package com.yingside.net.chat3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private boolean flag = true;
    public static void main(String[] args) {
        Client c = new Client();
        c.startup();
    }

    public void startup(){
        Socket s = null;
        try {
            s = new Socket("192.168.28.131",8888);

            //接收控制台输入的信息
//            BufferedReader br = null;
//            br = new BufferedReader(new InputStreamReader(System.in));

            Scanner input = new Scanner(System.in);


            PrintWriter out = new PrintWriter(s.getOutputStream(),true);

            System.out.println("请开始你的表演:");
            String str = null;

            try {
                //客户端子线程负责接收信息
                ClientThread ct = new ClientThread(s);
                Thread t = new Thread(ct);
                t.start();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //客户端主线程负责发送信息
            while(true){
                str = input.next();
                out.println(str);
                if(!flag){
                    System.out.println("bye bye!!");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(s != null){
                    s.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public class ClientThread implements Runnable{

        private Socket s;
        private BufferedReader sbr;
        private String serverBack;
        public ClientThread(Socket s) throws IOException {
            this.s = s;
            sbr = new BufferedReader(new InputStreamReader(s.getInputStream()));
        }

        @Override
        public void run() {
            try {
                while((serverBack = sbr.readLine()) != null){
                    if(serverBack.equals("exit")){
                        flag = false;
                        break;
                    }
                    System.out.println("serverBack = " + serverBack);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
